package cn.virens.web.components.websocket;

import java.security.Principal;
import java.util.Objects;

public class SimplePrincipal implements Principal {
	private String name;
	private String group;
	private String avatar;
	private String account;

	@Override
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getGroup() {
		return group;
	}

	public void setGroup(String group) {
		this.group = group;
	}

	public String getAvatar() {
		return avatar;
	}

	public void setAvatar(String avatar) {
		this.avatar = avatar;
	}

	public String getAccount() {
		return account;
	}

	public void setAccount(String account) {
		this.account = account;
	}

	@Override
	public boolean equals(Object obj) {
		if (obj instanceof SimplePrincipal) {
			return eq((SimplePrincipal) obj);
		} else {
			return false;
		}
	}

	@Override
	public int hashCode() {
		return Objects.hash(group, account);
	}

	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder();
		builder.append("SimplePrincipal [name=");
		builder.append(name);
		builder.append(", account=");
		builder.append(account);
		builder.append("]");
		return builder.toString();
	}

	public static String getGroup(Principal principal) {
		if (principal instanceof SimplePrincipal) {
			return ((SimplePrincipal) principal).getGroup();
		} else {
			return null;
		}
	}

	public static String getAccount(Principal principal) {
		if (principal instanceof SimplePrincipal) {
			return ((SimplePrincipal) principal).getAccount();
		} else {
			return null;
		}
	}

	private boolean eq(SimplePrincipal other) {
		if (this == other) { return true; }
		if (group == null || account == null) { return false; }
		if (group.equals(other.group) == false) { return false; }
		if (account.equals(other.account) == false) { return false; }

		return true;
	}

}
